var express = require("express");
var router = express.Router();
const fs = require("fs");
const fn = require("../src/fn");
const path = require("path");
const { basePath, pathType, status } = require("../src/config");
const multer = require("multer");
const myCustomStorage = require("../src/utils/MyCustomStorage");

const SparkMD5 = require("../public/javascripts/tools/md5.min.js");
const storage = myCustomStorage({
  destination: function (req, file, cb) {
    let {type} = req.body;
    cb(null, {path:'temp'+pathType+type});
  },
  filename: function (req, file, cb) {
    let {index} = req.body;
    cb(null, index );
  }
});
const upload = multer({ storage });

/* GET home page. */
router.post("/", function (req, res, next) {
  const { path, type ,sdkDir} = req.body;
  fn.unzip(path, type,sdkDir,false)
  res.send(status({}));
});


router.post("/inspectUpload",function (req, res, next) {
  // 判断是否存在文件夹
  const { type, md5,fileName,sdkDir } = req.body;
  // 对比版本号
  let typePath =
      type == "Android" ? pathType + "baseAndroidSDK" : pathType + "baseIosSDK";
  let oldVersion = fs.readFileSync(basePath + typePath + pathType + "_sdkVersion",);
  if (
    oldVersion == fileName &&
    fs.readdirSync(basePath + typePath).filter(item=>item != '.DS_Store').length > 1
  ) {
    console.log(`${typePath}版本号一致，不需要更新`);
    res.send(status({code:666,msg:'版本号一致，不需要更新',data:[666]}))
    return;
  }
  const dir = path.resolve(__dirname, "../temp/" + type);
  if (!fs.existsSync(dir)) {
    fs.mkdirSync(dir);
    // 通知客户端上传
    res.send(status({data:[],msg:'开始上传'}))
  }else{
    // 如果以前有 获取文件夹下面的文件是否有100个
    const files = fs.readdirSync(dir).filter(item=>item != '.DS_Store');
    // 删除文件夹下下面的.zip后缀
    files.forEach((item) => {
      if (item.includes(".zip")) {
        fs.unlinkSync(dir + "/" + item);
        files.splice(files.indexOf(item), 1);
      }
    });
    if(files.length >= 100){
      // 通知服务器整合文件
      fn.mergeFile(type, md5,fileName,sdkDir)
      res.send(status({data:[666],msg:'上传完成',code:666}))
    }else{
      let arr = []
      for(let i = 0;i<100;i++){
        if(!files.includes(i+'')) arr.push(i)
      }
      
      res.send(status({data:arr,msg:'继续上传'}))
    }
  }
});
router.post("/uploadchunk",upload.single("file"),function (req, res, next) {
  let file = fs.readFileSync(req.file.path);
  const { chunkMd5 } = req.body; 
  try{
    let md5 = SparkMD5.ArrayBuffer.hash(file.buffer);
    if(md5 !== chunkMd5){
      return res.send(status({code:400,msg:'md5不一致'}))
    }
    res.send(status({msg:'上传成功',data:req.file}));
  }catch(err){
    console.log(err)
     return res.send(status({code:400,msg:'上传失败'}))
  }
});

module.exports = router;
